package team.kirohuji.shiro.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import team.kirohuji.shiro.token.JWTToken;

public class JWTFilter extends AccessControlFilter {

	private Logger LOGGER = LoggerFactory.getLogger(this.getClass());

	public static final String DEFAULT_JWT_PARAM = "Authorization";

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		onAccessDenied(request, response);
		return true;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		if (isJwtSubmission(request)) {
			JWTToken token = createToken(request, response);
			try {
				System.out.println("过滤器认证");
				Subject subject = getSubject(request, response);
				subject.login(token);
				return true;
			} catch (AuthenticationException e) {
				/*WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());*/
				System.out.println(e.getStackTrace());
			}
		}
		// 如果用户没有身份验证，且没有jwt，则重定向到服务端登录
		return false;

	}

	protected JWTToken createToken(ServletRequest request, ServletResponse response) {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String jwt = httpRequest.getHeader(DEFAULT_JWT_PARAM);
		String host = request.getRemoteHost();
		return new JWTToken(jwt, null, host);
	}

	protected boolean isJwtSubmission(ServletRequest request) {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String jwt = httpRequest.getHeader(DEFAULT_JWT_PARAM);
		return (request instanceof HttpServletRequest) && StringUtils.isNotBlank(jwt);
	}

}
